package com.codes.controller;

import com.codes.core.common.CConstant;
import com.codes.core.common.enumtype.MenuType;
import com.codes.core.common.result.Result;
import com.codes.core.utils.UserUtil;
import com.codes.core.utils.tree.TreeUtil;
import com.codes.model.Role;
import com.codes.service.PermissionSV;
import com.codes.service.RolePermissionSV;
import com.codes.service.RoleSV;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Date 2020/5/26 20:17
 * @Created by peanut
 */
@RestController
@RequestMapping("/role")
@Api(tags = "角色接口")
public class RoleCtr {

    @Autowired
    private RoleSV roleSV;
    @Autowired
    private PermissionSV permissionSV;
    @Autowired
    private RolePermissionSV rolePermissionSV;

    @GetMapping("/getallrole")
    @ApiOperation("获取所有角色")
    public Result getAllRoles(){
        System.out.println("jin");

        return Result.success(roleSV.getAllRoles());

    }

    @ApiOperation("角色添加")
    @PostMapping("/add")
    public Result addRole(Role role){
        Integer id = role.getId();
        Map m =new HashMap();
        m.put("name",role.getName());
        Map roleMap = roleSV.getRole(m);
        if(null == id){

            if(null != roleMap) return Result.failed("角色名称已经存在");
            return Result.success(roleSV.insert(role));
        }else {
            Integer addId = MapUtils.getInteger(roleMap,"id");
            if(!id.equals(addId) && null != roleMap) return Result.failed("角色已经存在");
           int re = roleSV.updateByPrimaryKeySelective(role);
            return Result.success(re);
        }
    }

    @GetMapping("/getlist")
    @ApiOperation("获取角色列表")
    public Result getPage(@RequestParam( defaultValue="1",required=true) int   page,
                          @RequestParam( defaultValue="10",required=true) Integer limit,
                          @RequestParam Map<String,Object> map) {

        PageHelper.startPage(page,limit);
        // Map<String, Object> map =  new HashMap<>();
        List<Map<String, Object>> users = roleSV.getAllRoles();
        PageInfo<Map<String, Object>> info = new PageInfo< >(users);
        return Result.pages(info.getList(),(int)info.getTotal());

    }

    @GetMapping("/getrolemenu")
    @ApiOperation("获取所有角色")
    public Object getrolemenu(HttpServletRequest request){
        try {
            int roleId =0;
            Map map  = UserUtil.getSessionUser(request);
            if(null == map) return  Result.failed("登陆异常请检查登录","loginError");
            if(map.containsKey("roleId")) roleId = Integer.parseInt(map.get("roleId").toString());
            if(0 != roleId){
                List<Map<String,Object>> list  =permissionSV.selectPerByRoleId(roleId);
              //  Map<String,Object> returnMap = getAllMenus(list);
                Map<String,Object> returnMap = getLoginMenu(list);
                return returnMap;
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return  Result.failed();
    }


    @GetMapping("/getmenu")
    @ApiOperation("获取菜单树")
    public Result getMenu(){
        Map<String,Object> m = new HashMap<>();
      //  m.put("roleId",0);
        List<Map<String,Object>> list  =permissionSV.getAllPer();
        List<Map<String,Object>> returnMap =  TreeUtil.buildMenuTree(list,0);
        return Result.success(returnMap);

    }
    @GetMapping("/getmenu-by-role")
    @ApiOperation("获取菜单根据角色")
    public Result getMenuByRole(@RequestParam   Map<String,Object> map){

        Integer roleId = MapUtils.getInteger(map,"roleId");
        if(null != roleId){
            List<Map<String,Object>> list  =permissionSV.getAllPermission(map);
            return Result.success(list);
        }

        return Result.failed("获取失败");
    }

    @ApiOperation("角色授权")
    @PostMapping("/roleauthor")
    public Result roleAuthor(@RequestParam   Map<String,Object> map){
        //
        String ids = MapUtils.getString(map,"ids");
        Integer roleId = MapUtils.getInteger(map,"roleId");
        int re = 0;
        if(StringUtils.isNotBlank(ids)  && null != roleId ){
            re = permissionSV.deleteByRoleId(roleId);
            String[] strs = ids.split(",");
            List<String> idss = Arrays.asList(strs) ;
            if(null != idss && idss.size() > 0){
                //  先删除角色的  全部资源 再  循环添加 资源
                Map<String,Object> perMap = new HashMap<>();
                perMap.put("rid",roleId);
                for ( String id:idss ) {
                    Integer pid = Integer.parseInt(id);
                    perMap.put("pid",pid);
                    re =    rolePermissionSV.insertSelective(perMap);
                }
                if( re > 0 )
                    return Result.success("授权成功");
            }
        }
        return  Result.failed("角色授权失败");
    }

    @ApiOperation("删除角色")
    @PostMapping("/del")
    public Result delete(@RequestParam Map<String,Object> map){

        Integer id = MapUtils.getInteger(map,"id");
        int re  = 0;
        if(id!= null){
            re = roleSV.deleteByPrimaryKey(id);
            return Result.success("角色删除成功",re);
        }
        return Result.failed("角色删除失败");
    }

    // getLoginMenu

    /**
     *      returnMap.put("memberCenter",userMu);
     *         returnMap.put("contentManagement",facilityMu);
     *         returnMap.put("systemeSttings",sysMu);
     *         returnMap.put("seraphApi",docMu);
     * @param list
     * @return
     */
    public static Map<String,Object> getLoginMenu(List<Map<String,Object>> list){
        Map<String,Object> returnMap = new HashMap<>();
        returnMap.put(MenuType.getLabelByCode(1),TreeUtil.buildMenuTree(list,1));
        returnMap.put(MenuType.getLabelByCode(2),TreeUtil.buildMenuTree(list,2));
        returnMap.put(MenuType.getLabelByCode(3),TreeUtil.buildMenuTree(list,3));
        returnMap.put(MenuType.getLabelByCode(4),TreeUtil.buildMenuTree(list,4));
        return returnMap;
    }
//    // getAllMenu
//    public static Map<String,Object>  getAllMenus(List<Map<String,Object>> list){
//        Map<String,Object> returnMap = new HashMap<>();
//        List<Map<String,Object>> userMu = new ArrayList<>();
//        List<Map<String,Object>> facilityMu = new ArrayList<>();
//        List<Map<String,Object>> sysMu = new ArrayList<>();
//        List<Map<String,Object>> docMu = new ArrayList<>();
//        List<Map<String,Object>> userMu2 = new ArrayList<>();
//        List<Map<String,Object>> facilityMu2 = new ArrayList<>();
//        List<Map<String,Object>> sysMu2 = new ArrayList<>();
//        List<Map<String,Object>> docMu2 = new ArrayList<>();
//        List<Map<String,Object>> sanjiMu = new ArrayList<>();
//        for ( Map<String,Object> m:list                 ) {
//            if(m.containsKey("pid")){
//                if(CConstant.USERMANAGER.equals(m.get("pid").toString())){
//                    userMu.add(m);
//                }
//            }
//            if(m.containsKey("pid")){
//                if(CConstant.FACILITYMANAGER.equals(m.get("pid").toString())){
//                    facilityMu.add(m);
//                }
//            }
//            if(m.containsKey("pid")){
//                if(CConstant.SYSMANAGER.equals(m.get("pid").toString())){
//                    sysMu.add(m);
//                }
//            }
//            if(m.containsKey("pid")){
//                if(CConstant.DOCUMENT.equals(m.get("pid").toString())){
//                    docMu.add(m);
//                }
//            }
//        }
//        for ( Map<String,Object> cm: list ) { //  1 2 3
//            String pid = cm.get("pid").toString();
//            for (Map<String,Object> cm2: facilityMu ) {
//                String idd = cm2.get("id").toString();
//                if(pid.equals(idd)){
//                    facilityMu2.add(cm);
//                }
//                cm2.put("children",facilityMu2);
//            }
//            for (Map<String,Object> cm2: userMu ) {
//                String idd = cm2.get("id").toString();
//                if(pid.equals(idd)){
//                    facilityMu2.add(cm);
//                }
//                cm2.put("children",userMu2);
//            }
//            for (Map<String,Object> cm2: sysMu ) {
//                String idd = cm2.get("id").toString();
//                if(pid.equals(idd)){
//                    facilityMu2.add(cm);
//
//                }
//                cm2.put("children",sysMu2);
//            }
//            for (Map<String,Object> cm2: docMu ) {
//                String idd = cm2.get("id").toString();
//                if(pid.equals(idd)){
//                    facilityMu2.add(cm);
//                }
//                cm2.put("children",docMu2);
//            }
//        }
//        returnMap.put("memberCenter",userMu);
//        returnMap.put("contentManagement",facilityMu);
//        returnMap.put("systemeSttings",sysMu);
//        returnMap.put("seraphApi",docMu);
//        return returnMap;
//    }
    // end
}